import { createStore } from 'vuex'

const setLoaclStorage = state => {
  const { cartList } = state
  const cartListString = JSON.stringify(cartList)
  localStorage.cartList = cartListString
}

const getLocalStorage = () => {
  if (localStorage.cartList === undefined) {
    return {}
  } else {
    return JSON.parse(localStorage.cartList)
  }
  // return JSON.parse(localStorage.cartList) || {}
}

export default createStore({
  state: {
    cartList: getLocalStorage()
  },
  mutations: {
    changeCartItemInfo (state, payload) {
      const { shopId, productId, productInfo, changeNum } = payload
      const shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {}
      }
      let product = shopInfo.productList[productId]
      if (!product) {
        product = productInfo
        product.count = 0
      }
      product.count = Math.max(0, product.count + changeNum)
      // 数量有增加时变成勾选
      changeNum > 0 && (product.check = true)
      shopInfo.productList[productId] = product
      state.cartList[shopId] = shopInfo
      setLoaclStorage(state)
    },
    changeCartItemCheck (state, payload) {
      const { shopId, productId } = payload
      const product = state.cartList[shopId].productList[productId]
      product.check = !product.check
      setLoaclStorage(state)
    },
    changeShopName (state, payload) {
      const { shopId, shopName } = payload
      const shopInfo = state.cartList[shopId] || {
        shopId: '',
        productList: {}
      }
      shopInfo.shopName = shopName
      state.cartList[shopId] = shopInfo
      setLoaclStorage(state)
    },
    cleanCartProducts (state, payload) {
      const { shopId } = payload
      state.cartList[shopId].productList = {}
      setLoaclStorage(state)
    },
    setCartItemsChecked (state, payload) {
      const { shopId } = payload
      const products = state.cartList[shopId].productList
      if (products) {
        for (const key in products) {
          const product = products[key]
          product.check = true
        }
      }
      setLoaclStorage(state)
    }
  }
})
